package cl.ccs.migracionbcmc.connection;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

public class ConnectionFactory {

    private static final String JNDI_BIC = "jdbc/bic";
    private static final String JNDI_MOL_SYBASE = "jdbc/mol";
    private static final String JNDI_CONSULTA = "jdbc/consulta";
    private static final String JNDI_MOL_ORACLE = "jdbc/infocom";

    public ConnectionFactory() {
        super();
    }


    /**
     * @return
     * @throws SQLException
     */
    public static Connection getConnectionSybaseBIC() throws SQLException {
        Connection result = null;
        try {
            result = ConnectionManager.getJNDIConnection(JNDI_BIC);
        } catch (Exception e) {
            throw new SQLException(e.getMessage());
        }
        return result;
    }

    /**
     * @return
     * @throws SQLException
     */
    public static Connection getConnectionMOL() throws SQLException {
        Connection result = null;
        try {
            result = ConnectionManager.getJNDIConnection(JNDI_MOL_SYBASE);
        } catch (Exception e) {
            throw new SQLException(e.getMessage());
        }
        return result;
    }

    /**
     * @return
     * @throws SQLException
     */
    public static Connection getConnectionInfocom() throws SQLException {
        Connection result = null;
        try {
            result = ConnectionManager.getJNDIConnection(JNDI_MOL_ORACLE);
        } catch (Exception e) {
            throw new SQLException(e.getMessage());
        }
        return result;
    }


    /**
     * @return
     * @throws SQLException
     */
    public static Connection getConnectionConsulta() throws SQLException {
        Connection result = null;
        try {
            result = ConnectionManager.getJNDIConnection(JNDI_CONSULTA);
        } catch (Exception e) {
            throw new SQLException(e.getMessage());
        }
        return result;
    }

    /**
     * @param resources
     */
    public static void freeConnection(Object... resources) {
        try {
            for (int i = 0; i < resources.length; i++) {
                if (resources[i] != null) {
                    if (resources[i] instanceof Connection) {
                        Connection con = (Connection)resources[i];
                        if (!con.isClosed()) {
                            con.close();
                        }
                    } else if (resources[i] instanceof ResultSet) {
                        ResultSet rs = (ResultSet)resources[i];
                        if (!rs.isClosed()) {
                            rs.close();
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
